import setting from '@/settings'
import store from '../store'
import Oidc from 'oidc-client'

var mgr = new Oidc.UserManager(setting.openidConfig)

//Oidc.Log.logger = console;
//Oidc.Log.level = Oidc.Log.INFO;

mgr.events.addUserLoaded(function (user) {
  alert('New User Loaded')  
  console.log('New User Loaded：', arguments);
  console.log('Acess_token: ', user.access_token)
  
  //重新刷新用户
  store.dispatch('userService/setLoginedUser', user)
});

mgr.events.addAccessTokenExpiring(function () {
  alert('AccessToken Expiring')
  console.log('AccessToken Expiring：', arguments);
});
/**
 * token过期事件
 */
mgr.events.addAccessTokenExpired(function () {
  console.log('AccessToken Expired：', arguments);  
  alert('Session expired. Going out!');
  mgr.signoutRedirect().then(function (resp) {
    console.log('signed out', resp);
  }).catch(function (err) {
    console.log(err)
  })
  //accesstoken过期，重新登录
  //mgr.removeUser()
  //mgr.signinRedirect()
});

mgr.events.addSilentRenewError(function () {
  console.error('Silent Renew Error：', arguments);
  alert('Silent Renew Error：' + arguments)
});

mgr.events.addUserSignedOut(function () {
  alert('Going out!');
  console.log('UserSignedOut：', arguments);
  mgr.signoutRedirect().then(function (resp) {
    console.log('signed out', resp);
  }).catch(function (err) {
    console.log(err)
  })
  //mgr.removeUser()
  //重新跳转到登录页面
  //mgr.signinRedirect()
});

export default class SecurityService {

  // Renew the token manually
  renewToken () {
    let self = this
    return new Promise((resolve, reject) => {
      mgr.signinSilent().then(function (user) {
        if (user == null) {
          self.signIn(null)
        } else{
          return resolve(user)
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }
  signinSilentCallback(){
    let self = this
    return new Promise((resolve,reject) =>{
      mgr.signinSilentCallback().then(resp =>{
        resolve(resp)
      }).catch(err =>{
        reject(err)
      })
    })
  }

  // Get the user who is logged in
  getUser () {
    let self = this
    return new Promise((resolve, reject) => {
      mgr.getUser().then(function (user) {
        if (user == null) {
          self.signIn()
          return resolve(null)
        } else{          
          return resolve(user)
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }

  // Check if there is any user logged in
  getSignedIn () {
    let self = this
    return new Promise((resolve, reject) => {
      mgr.getUser().then(function (user) {
        if (user == null) {
          self.signIn()
          return resolve(user) //false
        } else{
          return resolve(user) //true
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }
  /**
   * 登录成功后跳转
   */
  signinRedirectCallback(){
    return new Promise((resolve, reject) => {
      mgr.signinRedirectCallback().then(resp =>{
        resolve(resp)
      }).catch(err =>{
        reject(err)
      })
    })
  }
  // Redirect of the current window to the authorization endpoint.
  signIn () {
    mgr.signinRedirect().catch(function (err) {
      console.log(err)
    })
  }
  
  
  getSignOut () {
    return new Promise((resolve, reject) => {   
      mgr.signoutRedirect().then(function (resp) {
        console.log('signed out', resp);
        resolve(resp)
      }).catch(function (err) {
        console.log(err)
        reject(err)
      })
    }) 
  }

  // Redirect of the current window to the end session endpoint
  signOut () {    
    mgr.signoutRedirect().then(function (resp) {
      console.log('signed out', resp);
    }).catch(function (err) {
      console.log(err)
    })
  }

  // Get the profile of the user logged in
  getProfile () {
    let self = this
    return new Promise((resolve, reject) => {
      mgr.getUser().then(function (user) {
        if (user == null) {
          self.signIn()
          return resolve(null)
        } else{          
          return resolve(user.profile)
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }

  // Get the token id
  getIdToken(){
    let self = this
    return new Promise((resolve, reject) => {
      mgr.getUser().then(function (user) {
        if (user == null) {
          self.signIn()
          return resolve(null)
        } else{          
          return resolve(user.id_token)
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }

  // Get the session state
  getSessionState(){
    let self = this
    return new Promise((resolve, reject) => {
      mgr.getUser().then(function (user) {
        if (user == null) {
          self.signIn()
          return resolve(null)
        } else{          
          return resolve(user.session_state)
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }

  // Get the access token of the logged in user
  getAcessToken(){
    let self = this
    return new Promise((resolve, reject) => {
      mgr.getUser().then(function (user) {
        if (user == null) {
          self.signIn()
          return resolve(null)
        } else{          
          return resolve(user.access_token)
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }

  // Takes the scopes of the logged in user
  getScopes(){
    let self = this
    return new Promise((resolve, reject) => {
      mgr.getUser().then(function (user) {
        if (user == null) {
          self.signIn()
          return resolve(null)
        } else{          
          return resolve(user.scopes)
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }

  // Get the user roles logged in
  getRole () {
    let self = this
    return new Promise((resolve, reject) => {
      mgr.getUser().then(function (user) {
        if (user == null) {
          self.signIn()
          return resolve(null)
        } else{          
          return resolve(user.profile.role)
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }
}
